package com.lovo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lovo.model.Commodity;
import com.lovo.service.CommodityService;
import com.lovo.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * @Author:kyle
 * @Date:2020/11/26 - 14:20
 * @Project:pet_sys
 * @Package:com.lovo.service.impl
 * @Version:1.0
 */
public class CommodityServiceImpl implements CommodityService {
    /**
     * 商品详情，可选择查询并分页
     * @param pageNo 页码
     * @param pageSize 每页显示条目
     * @param commodityName 商品名
     * @param commodityType 品类
     * @return
     */
    public PageInfo<Commodity> listsBySelective(int pageNo, int pageSize, String commodityName, String commodityType) {
        // 创建sqlSession
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        String stmt = "com.lovo.dao.CommodityMapper.listsBySelective";
        // 分页拦截
        PageHelper.startPage(pageNo,pageSize);
        // 封装查询对象
        Commodity c = new Commodity();
        c.setCommodityName(commodityName);
        c.setCommodityType(commodityType);

        List<Commodity> commodityList = sqlSession.selectList(stmt, c);
        PageInfo<Commodity> pageInfo = new PageInfo<>(commodityList);

        SqlSessionUtil.commit();
        return pageInfo;
    }

    /**
     * 根据主键删除商品
     *
     * @param commodityId 商品id
     * @return
     */
    public boolean deleteByPrimaryKey(Integer commodityId) {
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        String stmt = "com.lovo.dao.CommodityMapper.deleteByPrimaryKey";

        int n = sqlSession.delete(stmt,commodityId);
        SqlSessionUtil.commit();
        return n > 0 ?true:false;
    }

    /**添加商品
     * @param record 商品对象
     * @return
     */
    public boolean insertCommodity(Commodity record) {
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        String stmt = "com.lovo.dao.CommodityMapper.insertCommodity";

        int n = sqlSession.insert(stmt,record);
        SqlSessionUtil.commit();
        return n > 0 ?true:false;
    }

    /**
     *
     * @param record
     * @return
     */
    public boolean updateBySelective(Commodity record) {
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        String stmt = "com.lovo.dao.CommodityMapper.updateBySelective";

        int n = sqlSession.update(stmt,record);
        SqlSessionUtil.commit();
        return n > 0 ?true:false;
    }

    @Override
    public Commodity selectByPrimaryKey(Integer commodityId) {
        SqlSession sqlSession = SqlSessionUtil.getSqlSession();
        String stmt = "com.lovo.dao.CommodityMapper.selectByPrimaryKey";
        Commodity commodity = sqlSession.selectOne(stmt, commodityId);
        SqlSessionUtil.commit();
        return commodity;
    }

}
